package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import util.JwtUtil;

/**
 * jwt 拦截器.
 *
 * @author 宫新程
 * @since 2019/3/16 13:31
 */
public class JwtInterceptor implements HandlerInterceptor {

  @Resource private JwtUtil jwtUtil;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    /** 无论如何都要放行，具体能不能操作还是在具体的操作中去判断.
     *  拦截器只是负责把头请求中包含token的令牌进行解析. */

    // 获取请求头
    String header = request.getHeader("Authorization");
    // 如果包含有 Authorization 头信息 则进行解析
    if (StringUtils.isNotBlank(header)) {
      if (!header.startsWith("Bearer ")) {
        throw new RuntimeException("权限不足");
      }
      // 获取token
      String token = header.replace("Bearer ", "");
      // 解析token
      Claims claims = jwtUtil.parseJWT(token);
      // 获取权限
      String roles = claims.get("roles", String.class);
      // 如果是admin权限
      if (StringUtils.isNotBlank(roles) && "admin".equals(roles)) {
        request.setAttribute("claims_admin", claims);
      }
      // 如果是user权限
      if (StringUtils.isNotBlank(roles) && "user".equals(roles)) {
        request.setAttribute("claims_user", claims);
      }
    }
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {}

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {}
}
